package it.sd.wdc.spider.bean;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.StringTokenizer;

public class PostParameters {

	private LinkedHashMap<String, String> parameters = new LinkedHashMap<String, String>();
	
	public void addParameter(String codice, String valore) {
		parameters.put(codice, valore);
	}

	public Iterator<String> iterateParameters() {
		return parameters.keySet().iterator();
	}
	
	public String getValue(String key) {
		return parameters.get(key);
	}
	
	public String toString() {
		StringBuffer buffer = new StringBuffer();
		
		buffer.append(parameters);
			
		return buffer.toString();
	}
	
	
	public String getPostAsString() throws Exception {

		StringBuffer sb = new StringBuffer();
		for (Iterator<String> iter = parameters.keySet().iterator(); iter.hasNext();) {
			if (sb.length() > 0) {
				sb.append("&");
			}
			String key = iter.next();
			String valore = getValue(key);
			if (valore!=null) {
				sb.append(key+ "=" + URLEncoder.encode(getValue(key), "UTF-8"));
			}
		}
		
		return sb.toString();
	}

	public void addParameters(String post) throws Exception {
		
		StringTokenizer st = new StringTokenizer(post, ",");
		while (st.hasMoreTokens()) {
			String sp = st.nextToken();
			StringTokenizer pt = new StringTokenizer(sp, "=");
			if (pt.countTokens() > 0) {
				String name = pt.nextToken();
				String value = "";
				if (pt.hasMoreTokens()) {
					value = pt.nextToken();
					value = URLDecoder.decode(sp, "UTF-8");
					if (value == null) value = "";
				}
				addParameter(name, value);
			}
		}
	}
	
	public LinkedList<String[]> getNameValuePair() {

		LinkedList<String[]> valori = new LinkedList<String[]>();
		
		for (Iterator<String> iter = parameters.keySet().iterator(); iter.hasNext();) {
			String parm[] = new String[2];
			String key = iter.next();
			String valore = getValue(key);
			parm[0] = key;
			parm[1] = valore;
			valori.add(parm);
		}
		
		return valori;
		
	}
	
}
